<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;
use think\File;
use think\Config;
use think\Exception;
use app\common\model\User;
use app\common\model\Money;
use app\common\model\Attachment;
use app\common\model\WalletLog;
use app\common\model\IntegralLog;
use app\common\model\Business;
use OSS\OssClient;
use OSS\Core\OssException;
use app\common\model\Pay_num;
use app\common\model\Reward;
use app\common\model\UserLevel;
use app\common\model\Gongpai;

/**
 * 记录帐户变动
 * @param int $user_id 用户id
 * @param float $user_money 可用GMOB变动
 * @param string $desc 变动说明
 * @param int $fee  手续费
 * @param string $bond 保证金
 * @param float $frozen_money 冻结资金
 * @param int $user_money 奉献值
 * @return bool
 */
function accountLog($user_id, $money = 0, $desc = '', $fee = 0, $bond = '', $frozen_money = 0, $user_money = 0)
{
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id' => $user_id,
        'money' => $user_money,
        'create_time' => time(),
        'frozen_money' => $frozen_money,
        'user_money' => $user_money,
        'desc' => $desc,
        'fee' => $fee,
        'bond' => $bond
    );
    $data = Db::name('account_log')->insert($account_log);
    if ($data) {
        return true;
    } else {
        return false;
    }

}

/** 
 * 买出冻结金额
 * @param $id  用户id
 * @param $money  所需要的金额
 * @param $type 状态true 扣除金额 增加冻结金额 false  只取消冻结金额
 * @param $wallet_num 保证金 退会保证金
 * @param $status  判断是否冻结资金
 * @param $num   消费明细
 * @param $discount_ratio  打折优惠
 * @return  array  status  1  成功    
 */
function sale_amount($id, $money, $type = true, $wallet_num, $status = true,$num,$discount_ratio)
{
    Db::startTrans();
    $user = Money::where('uid', $id)->find();
    if ($user == "") {
        Db::rollback();
        return array('status' => 0, 'msg' => lang("买入失败"));
    }
    $user_money = bcsub($user->wallet_num, $money, 2);
    if (bccomp($user_money, '0', 2) < 0) {
        Db::rollback();
        return array('status' => 0, 'msg' => lang("GMOB不足"));
    }
    $frozen_money = bcadd($user->frozen_money, $money, 2);
    if ($type) {
        if (!walletLog($id, -$money, $user->wallet_num, $num)) {
            Db::rollback();
            return array('status' => 0, 'msg' => lang("买入失败"));
        }
        $user->wallet_num = $user_money;
        if ($status) {
            $user->frozen_money = $frozen_money;
        }

    } else {
        if (!walletLog($id, $wallet_num, $user->wallet_num, $num)) {
            Db::rollback();
            return array('status' => 0, 'msg' => lang("买入失败"));
        }
        $user->wallet_num = $user->wallet_num + $wallet_num;
        $user->frozen_money = $frozen_money;
    }
    if($discount_ratio != "0"){
        $total = $user->integral_num;
        $user->integral_num = $user->integral_num + $discount_ratio;
        $result= [
            'userid' =>$id,
            'num'    => $discount_ratio,
            'type'   => 13,
            'before_integral' => $total,
            'now_integral'    => $user->integral_num,
            'create_time'    => time()
         ];
       
       $data= IntegralLog::create($result);
       if(!$data->id){
            Db::rollback();
            return array('status' => 0, 'msg' => lang("买入失败"));  
       }
    }
    $save = $user->save();
    if ($save) {
        Db::commit();
        return array('status' => 1, 'msg' => lang("买入成功"));
    } else {
        Db::rollback();
        return array('status' => 0, 'msg' => lang("买入失败"));
    }

}
/** 
 * 登录支付密码加密
 * @param $pwd 密码
 * @param $salt 密码
 */
function pwdMd5($pwd, $salt)
{
     $user_pwd = md5(md5($pwd) . $salt);
     return $user_pwd;
}

/** 
 * 验证支付密码
 * @param $user_id 用户id
 * @param $payment_pwd  支付密码
 */
function encrypt($user_id, $pwd)
{
    $user = User::get($user_id);
    $pwd = md5(md5($pwd) . $user['safety_salt']);
    if ($user['safety_pwd'] == $pwd) {
        return true;
    } else {
        return false;
    }
}
/** 
 * 上传文件
 * @param $file  文件上传信息
 * @param $size 文件上传大小
 * @return  string  url 图片的路径
 */
function fileupload($file, $size = 2048000)
{
    if ($file) {
        $img = $file->validate(['size' => $size, 'ext' => 'jpg,png,gif,jpeg,bmp'])->move(Env::get('root_path') . 'public/uploads');
        if($img){
              $path = str_replace("\\", "/", $img->getSaveName());
              return $pic = '/uploads/' . $path;
        }else{
            $error = $file->getError();
            return ['status'=>3,'msg'=>$error];
        }
    }
    return false;

}


/**
 * GMOB变动记录表
 * @param  $userid  用户的id
 * @param  $money  转账金额
 * @param  int    $type 类型  
 * @param  $before_wallet  交易前的GMOB
 * @return  $userid添加数据的
 * 
 */
function walletLog($user_id, $money, $before_wallet, $type)
{
    if($money == ''){
        return false;
    }
    $now_wallet = bcadd($before_wallet, $money, 4);
    $array = array(
        'userid' => $user_id,
        'money' => $money,
        'type' => $type,
        'before_wallet' => $before_wallet,
        'now_wallet' => $now_wallet
    );
    $result = WalletLog::create($array);
    return $result->userid;
}



/**  
*转载自：http://www.jb51.net/article/56967.htm
* @desc 根据两点间的经纬度计算距离 
* @param float $lat 纬度值 
* @param float $lng 经度值 
*/ 
function getDistance($lat1, $lng1, $lat2, $lng2){ 
    $earthRadius = 6367000; //approximate radius of earth in meters 
    $lat1 = ($lat1 * pi() ) / 180; 
    $lng1 = ($lng1 * pi() ) / 180; 
    $lat2 = ($lat2 * pi() ) / 180; 
    $lng2 = ($lng2 * pi() ) / 180; 
    $calcLongitude = $lng2 - $lng1;   
    $calcLatitude = $lat2 - $lat1; 
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); 
    $stepTwo = 2 * asin(min(1, sqrt($stepOne))); 
    $calculatedDistance = $earthRadius * $stepTwo; 
    return round($calculatedDistance); 
    }

/**
 * 多维数组排序
 * @param array $array 要排序的数组
 * @param string $key 排序依据字段
 * @param string $order 排序方式，0为降序，1为升序
 */
function array_sort($array,$key,$order=1){
    $sort=[];
//    在此处形成字段值与键名的对应关系
    foreach($array as $k=>$v){
        $sort[$v[$key]]=isset($sort[$v[$key]])?array_merge($sort[$v[$key]],[$k]):[$k];
    }
    if($order==1&&ksort($sort)){
//        升序排序
 
    }elseif($order==0&&krsort($sort)){
 
    }else{
        return false;
    }
    $rs = [];
//    按照排好顺序的关系生成新的数组
    foreach($sort as $value){
        foreach($value as $n){
            $rs[] = $array[$n];
        }
    }
    unset($sort,$array);
    return $rs;
}


/**
 * OSS简单上传  将阿里云ossSDK包中的OSS文件夹放在项目extend目录下
 * 需要客户端将文件上传到服务器端之后，获取文件在服务器端的路径再调用
 * @param string $filePath  文件在服务器的相对路径
 * @param string $dir  上传到bucket下的相对目录，以'/'结尾
 * @return mixed  上传成功后，文件的CDN访问地址,出错则打印出错信息
 */
function simpleUpload($filePath, $dir = null, $bucket = '')
{   
    $endpoint = 'http://oss-cn-beijing.aliyuncs.com';
    $accessKeyId = 'LTAImUgOMuAfoOal';
    $accessKeySecret = '9HdRCsBk2S78ikV1WOMveTz05SgRgS'; 
    $bucket = 'rzdoss';
    // 文件名称
    $nonce = getNonceStr();
    //上传文件后缀
    $ext = getExtension($filePath);
    $object = $nonce . '.' . $ext;
    if(isset($dir) && !empty($dir))
        $object = $dir . $nonce . '.' . $ext;
    
    // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
    try{
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $info = $ossClient->uploadFile($bucket, $object, $filePath);
        // print_r($info);
        return $info['oss-request-url'];
    } catch(OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }
}


//随机字符串
function getNonceStr()
{
    //生成16位随机字串
    $charts = 'abcdefghijklmnopqrstuvwxyz1234567890';
    $max = strlen($charts);
    $noncestr = '';
    for($i=0; $i<16; $i++){
        $noncestr .= $charts[mt_rand(0, $max-1)];
    }
    return $noncestr;
}


//获取上传文件后缀名
function getExtension($filePath)
{
    $arr = pathinfo($filePath);
    return $ext = $arr['extension'];
}
//使用GMOB时判断GMOB是否足够
/**
 * $uid 当前登录用户的userid
 **/
function check_yue($uid){
    $yue_num1 = WalletLog::where([ 'userid' => $uid,'type'=>	[2,3,4,5,6,7,8,9,11,13,14,15,16,17,18,19,20,21,22,23]])->sum('money');
    $yue_num2 = WalletLog::where([ 'userid' => $uid,'type'=>	[1,12]])->sum('money');
    $yue_num = $yue_num1-$yue_num2;
    return $yue_num;
}

/**
 * 查询用户信息
 *
 * @param      <string>   $userid  用户ID
 *
 * @return     boolean  返回用户信息
 */
function get_user_info($userid)
{
    if(!$userid)
        return false;

    return $user = User::get($userid);
}

/**
 * 查询商户信息
 *
 * @param      <string>   $userid  用户ID
 *
 * @return     boolean  返回商户信息
 */
function get_shop_info_by_uid($userid)
{
    if(!$userid)
        return false;

    return $user = Business::where(['userid'=>$userid])->find();
}


/**
 * 验证支付密码 并记录错误次数
 * @param $user_id 用户id
 * @param $pwd 支付密码
 */
function pwd_error_num($user_id,$pwd)
{

    $user = User::get($user_id);
    //获取用户支付次数信息
    $paynums = Pay_num::where(array('userid'=>$user_id))->find();
    $user = User::get($user_id);
    $pwd = md5(md5($pwd) . $user['safety_salt']);
    if ($user['safety_pwd'] == $pwd) {
        //密码正确
        if($paynums){
            $times = time();
            $rtime = $times-strtotime($paynums['create_time']);
            //3小时以内
            if($rtime < 10800){
                //判断次数
                if($paynums['num']>=5){
                    //锁定24小时
                    return '5';
                }else{
                    //清除数据
                    Pay_num::where(array('userid'=>$user_id))->delete();
                    //支付成功
                    return '0';
                }
            }
        }else{
            return '0';
        }


    } else {
        //密码错误 3小时内连续错误5次 锁定3小时
        if(!$paynums){
            //错误次数+1
            $data = ['userid'=>$user_id,'num'=>'1','create_time'=>time()];
            Pay_num::insert($data);
            //返回错误次数
            return $paynums['num']+1;
        }else{
            //获取时间间隔
            $time = time();
            $gtime = $time - strtotime($paynums['create_time']);
            //大于24小时 清除数据 重新插入
            if($gtime > 10800){
                Pay_num::where(array('userid'=>$user_id))->delete();
                $data1 = ['userid'=>$user_id,'num'=>'1','create_time'=>time()];
                Pay_num::insert($data1);
                return '1';
            }else{
                //24小时以内
                if($paynums['num'] >= 5 ){
                    return '5';
                }else{
                    //次数+1
                    Pay_num::where(array('userid'=>$user_id))->setInc('num',1);
                    return $paynums['num']+1;
                }
            }

        }

    }

}

//返回json格式数据
function json_return($status,$message){
    $mes = ['status'=>$status,'message'=>lang($message)];
    return json_encode($mes);
}

/**
 * 通过CURL发送HTTP请求
 * @param string $url  //请求URL
 * @param array $postFields //请求参数
 * @return mixed
 */
function curlPost($url,$postFields){
    $postFields = json_encode($postFields);
    $ch = curl_init ();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8'
        )
    );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt( $ch, CURLOPT_TIMEOUT,10);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
    $ret = curl_exec ( $ch );
    if (false == $ret) {
        $result = curl_error(  $ch);
    } else {
        $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
        if (200 !== $rsp) {
            $result = "请求状态 ". $rsp . " " . curl_error($ch);
        } else {
            $result = $ret;
        }
    }
    curl_close ( $ch );
    return $result;
}
//直推奖和辅导奖
function cengji($userid,$money,$yue)
{
    $path = User::where('id', $userid)->value('path');
    if ($path != '') {
        $path = rtrim($path, ',');
        $path = explode(',', $path);
        //print_r($path);
        krsort($path);
        $arr = array();
        foreach ($path as $value) {
            $arr[] = $value;
        }
        //直推奖配置
        $zhitui_wallet = Reward::where('group',1)->where('field','direct_wallet')->value('value');
        $zhitui_integral = Reward::where('group',1)->where('field','direct_integral')->value('value');
        Db::startTrans();
        try{
            if(count($arr)){
                //分配直推奖
                $parent_money =  Money::where('userid',$arr[0])->find();
                //写入GMOB记录表
                $data['userid'] = $arr[0];
                $data['money'] = $yue*$zhitui_wallet/100;
                $data['before_wallet'] = $parent_money['balance'];
                $data['now_wallet'] =  $parent_money['balance'] + $yue*$zhitui_wallet/100;
                $data['type'] = 1;//直推奖
                $data['from_userid'] = $userid;
                $data['create_time'] = time();
                $result = WalletLog::insert($data);
                //增加GMOD
                $data1['userid'] = $arr[0];
                $data1['num'] = $money*$zhitui_integral/100;
                $data1['type'] = 1;//直推奖
                $data1['before_integral'] = $parent_money['integral'];//交易之前的GMOD
                $data1['now_integral'] = $parent_money['integral']+$money*$zhitui_integral/100;//交易之后的GMOD
                $data1['create_time'] = time();
                $data1['from_userid'] = $userid;
                $res1 = IntegralLog::insert($data1);
                if($result && $res1){
                    Money::where('userid',$arr[0])->update(['balance'=> $data['now_wallet'],'integral'=> $data1['now_integral']]);
                }
                foreach($arr as $key=>$value){
                    $level_grade = UserLevel::where('userid',$value)->value('user_grade');
                    //辅导奖
                    if($key<9){
                        if($level_grade >= $key+1){
                            $cengji_money =  Money::where('userid',$value)->find();
                            //辅导奖配置
                            $counseling_award = Reward::where('group',2)->where('tip',$key+1)->value('value');
                            //增加GMOD
                            $data2['userid'] = $value;
                            $data2['num'] = $money*$counseling_award/100;
                            $data2['type'] = 2;//辅导奖
                            $data2['from_userid'] = $userid;
                            $data2['before_integral'] = $cengji_money['integral'];//交易之前的GMOD
                            $data2['now_integral'] = $cengji_money['integral']+$money*$counseling_award/100;//交易之后的GMOD
                            $data2['create_time'] = time();
                            $res2 = IntegralLog::insert($data2);
                            if($res2){
                                Money::where('userid',$value)->setInc('integral',$money*$counseling_award/100);
                            }
                        }
                    }
                }
                Db::commit();
                return true;
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }
}
/**
**团队业绩GMOD奖励
 **/
function team_integral($userid,$money){
    $path = User::where('id', $userid)->value('path');
    if ($path != '') {
        $path = rtrim($path, ',');
        $path = explode(',', $path);
        //print_r($path);
        krsort($path);
        $arr = array();
        foreach ($path as $value) {
            $arr[] = $value;
        }
        $jiedian = 0;
        $super_jiedian = 0;
        $shequ = 0;
        foreach($arr as $key=>$value){
            $level_grade = UserLevel::where('userid',$value)->value('level_grade');
            //寻找上级是节点的
            if($jiedian == 0 && $level_grade ==1){
                $config = Reward::where('id',7)->value('value');
                $cengji_money =  Money::where('userid',$value)->find();
                //增加GMOD
                $data2['userid'] = $value;
                $data2['num'] = $money*$config/100;
                $data2['type'] = 9;
                $data2['from_userid'] = $userid;
                $data2['before_integral'] = $cengji_money['integral'];//交易之前的GMOD
                $data2['now_integral'] = $cengji_money['integral']+$money*$config/100;//交易之后的GMOD
                $data2['create_time'] = time();
                $res2 = IntegralLog::insert($data2);
                if($res2){
                    Money::where('userid',$value)->setInc('integral',$money*$config/100);
                    $jiedian =1;
                }
            }elseif($super_jiedian == 0 && $level_grade ==2){
                $config = Reward::where('id',8)->value('value');
                if($jiedian == 1){
                    $config1 = Reward::where('id',7)->value('value');
                    $config = $config-$config1;
                }
                $cengji_money =  Money::where('userid',$value)->find();
                //增加GMOD
                $data2['userid'] = $value;
                $data2['num'] = $money*$config/100;
                $data2['type'] = 10;
                $data2['from_userid'] = $userid;
                $data2['before_integral'] = $cengji_money['integral'];//交易之前的GMOD
                $data2['now_integral'] = $cengji_money['integral']+$money*$config/100;//交易之后的GMOD
                $data2['create_time'] = time();
                $res2 = IntegralLog::insert($data2);
                if($res2){
                    Money::where('userid',$value)->setInc('integral',$money*$config/100);
                    $jiedian = 1;
                    $super_jiedian =1;
                }
            }elseif($shequ == 0 && $level_grade ==3){
                $config = Reward::where('id',9)->value('value');
                if($super_jiedian == 1){
                    $config1 = Reward::where('id',8)->value('value');
                    $config = $config-$config1;
                }
                $cengji_money =  Money::where('userid',$value)->find();
                //增加GMOD
                $data2['userid'] = $value;
                $data2['num'] = $money*$config/100;
                $data2['type'] = 11;
                $data2['from_userid'] = $userid;
                $data2['before_integral'] = $cengji_money['integral'];//交易之前的GMOD
                $data2['now_integral'] = $cengji_money['integral']+$money*$config/100;//交易之后的GMOD
                $data2['create_time'] = time();
                $res2 = IntegralLog::insert($data2);
                if($res2){
                    Money::where('userid',$value)->setInc('integral',$money*$config/100);
                    $jiedian = 1;
                    $super_jiedian =1;
                    $shequ =1;
                }
            }
        }
    }
}
/**
**加权分红奖
 **/
function dividend($userid,$money){
    $user_list = User::alias('u')->Join('langjin_user_level l','u.id = l.userid')->where('l.user_grade','in',('7,8,9'))->field(['u.id','l.user_grade'])->select();
    foreach($user_list as $key=>$value){
        $config = Reward::where(['group'=>5,'tip'=>$value['user_grade']])->value('value');
        $cengji_money =  Money::where('userid',$value['id'])->find();
        //增加GMOD
        $data2['userid'] = $value['id'];
        $data2['num'] = $money*$config/100;
        $data2['type'] = 12;
        $data2['from_userid'] = $userid;
        $data2['before_integral'] = $cengji_money['integral'];//交易之前的GMOD
        $data2['now_integral'] = $cengji_money['integral']+$money*$config/100;//交易之后的GMOD
        $data2['create_time'] = time();
        $res2 = IntegralLog::insert($data2);
        if($res2){
            Money::where('userid',$value['id'])->setInc('integral',$money*$config/100);
        }
    }
}
/**
点位奖
 **/
function make_point($userid,$money,$qu_id){
    $count =  Gongpai::where(['qu_id'=>$qu_id,'userid'=>$userid])->count();
    if($count){
        return false;
    }
    $gongpai_count = Gongpai::where('qu_id',$qu_id)->count();
    if($gongpai_count ==0){
        //如果该层级还没有公排数据，直接添加
        $data['userid'] = $userid;
        $data['qu_id'] = $qu_id;
        $data['ceng_id'] = 1;
        $data['pid'] = 0;
        $data['create_time'] = time();
        $new_id = Gongpai::insertGetId($data);
    }else{
        //如果已经有数据的话，找出最后一条数据
        $last_info = Gongpai::where(['qu_id'=>$qu_id,'is_out'=>0])->limit(1)->order('id desc')->find();
        //计算最后一条数据该层级应该有的人数
        $should_count = pow(3,$last_info['ceng_id']-1);
        //计算最后一条数据该层级实际有的人数
        $this_count = Gongpai::where(['qu_id'=>$last_info['qu_id'],'ceng_id'=>$last_info['ceng_id']])->count();
        if($this_count >=$should_count){
        //如果该层级已满,层级往下顺延+1
            $data['ceng_id'] = $last_info['ceng_id']+1;
            $data['qu_id'] = $last_info['qu_id'];
            $data['userid'] = $userid;
            $data['create_time'] = time();
            $pid_info =  Gongpai::where(['qu_id'=>$last_info['qu_id'],'ceng_id'=>$last_info['ceng_id'],'child_status'=>0])->limit(1)->order('id asc')->find();
            $data['pid'] = $pid_info['id'];
            $new_id = Gongpai::insertGetId($data);
            $child_count = Gongpai::where(['qu_id'=>$last_info['qu_id'],'pid'=>$pid_info['id']])->count();
            if($child_count>=3){
                Gongpai::where(['id'=>$pid_info['id']])->update(['child_status'=>1]);
            }
        }else{
            //如果该层级没满，还在该层级添加
            $data['ceng_id'] = $last_info['ceng_id'];
            $data['qu_id'] = $last_info['qu_id'];
            $data['userid'] = $userid;
            $data['create_time'] = time();
            $parent_info = Gongpai::where(['qu_id'=>$last_info['qu_id'],'ceng_id'=>$last_info['ceng_id']-1,'child_status'=>0])->limit(1)->order('id asc')->find();
            $data['pid'] = $parent_info['id'];
            $new_id = Gongpai::insertGetId($data);
            $child_count = Gongpai::where(['qu_id'=>$last_info['qu_id'],'pid'=>$parent_info['id']])->count();
            if($child_count>=3){
                Gongpai::where(['id'=>$parent_info['id']])->update(['child_status'=>1]);
            }
        }
    }
    //看看自己的冻结奖励有没有可以释放的
    $user_grade = UserLevel::where('userid',$userid)->value('user_grade');
    $dongjie_list = IntegralLog::where(['userid'=>$userid,'status'=>1,'type'=>15,'dai'=>$user_grade])->select();
    $cengji_money =  Money::where('userid',$userid)->find();
    if($dongjie_list){
        foreach($dongjie_list as $value){
            //如果存在可以释放的冻结奖励
            $data2['id'] = $value['id'];
            $data2['before_integral'] = $cengji_money['integral'];//交易之前的GMOD
            $data2['now_integral'] = $cengji_money['integral']+$value['num'];//交易之后的GMOD
            $data2['create_time'] = time();
            $data2['status'] = 0;
            $res2 = IntegralLog::update($data2);
            if($res2){
                Money::where('userid',$userid)->setInc('integral',$value['num']);
            }
        }
    }
   //分配见点奖
    distribution_jiandian($userid,$new_id,$money);
}
/**
//分配见点奖
 **/
function distribution_jiandian($userid1,$id,$money){
    $str =array();
    $dai = 0;
    $arr1 = digui($id,$str,$dai);
    //print_r($arr1);exit;
    //见点奖
    $config = Reward::where('field','jiandian_award')->value('value');
    $jiandian_jiang = $money*$config/100;
    if($jiandian_jiang>0){
        foreach($arr1 as $key=>$value){
            //增加GMOD
            $userid = Gongpai::where('id',$value)->value('userid');
            $qu_id = Gongpai::where('id',$value)->value('qu_id');
            $cengji_money =  Money::where('userid',$userid)->find();
            //查找$userid的会员等级
            $user_grade = UserLevel::where('userid',$userid)->value('user_grade');
            if($user_grade <$key+1){
                //如果userid的等级小于当前代数冻结奖励
                $data1['userid'] = $userid;
                $data1['num'] = $jiandian_jiang;
                $data1['type'] = 15;//见点奖
                $data1['from_userid'] = $userid1;
                $data1['status'] = 1;//冻结奖励
                $data1['dai'] = $key+1;//冻结奖励
                $data1['create_time'] = time();
                $data1['qu_id'] = $qu_id;
                $res2 = IntegralLog::insert($data1);
            }else{
                $data2['userid'] = $userid;
                $data2['num'] = $jiandian_jiang;
                $data2['type'] = 15;//见点奖
                $data2['from_userid'] = $userid1;
                $data2['before_integral'] = $cengji_money['integral'];//交易之前的GMOD
                $data2['now_integral'] = $cengji_money['integral']+$jiandian_jiang;//交易之后的GMOD
                $data2['create_time'] = time();
                $data2['status'] = 0;
                $data2['qu_id'] = $qu_id;
                $res2 = IntegralLog::insert($data2);
                if($res2){
                    Money::where('userid',$userid)->setInc('integral',$jiandian_jiang);
                }
            }
        }
    }
}
function digui($id,&$str,$dai){
    $pid = Gongpai::where('id',$id)->value('pid');
    $dai++;
    if($pid !=0){
        $str[$dai]= $pid;
        if($dai<9){
            digui($pid,$str,$dai);
        }
    }
    return $str;
}
//清除上月冻结奖励
function clear_jiangli($userid){
    $info = IntegralLog::where(['userid'=>$userid,'status'=>1])->select();
    $now_time = date('m',time());
    foreach($info as $value){
        $thistime = strtotime($value['create_time']);
        $thistime =date('m',$thistime);
        if($thistime != $now_time){
            IntegralLog::where('id',$value['id'])->delete();
        }
    }
    /*
*生成token
*/
    function createToken($uid, $timestamp)
    {
        //$user = new User();
        //$salt = User::where(['id' => $uid])->field('salt')->find();
        //$userSalt = $salt['salt'];
        $cipherText = encrypts($uid . $timestamp, 'E', 'dj');
        $token = base64_encode($uid . '_' . $timestamp . '_' . $cipherText);
        return $token;
    }
}